package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import pojo.Host;
import servlet.HttpServlet;
import util.MyClassLoad;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    //定义socket监听的端口号
    private Integer port = 8080;

    public Integer getPort() {
        return port;
    }

    private Host host;

    public Host getHost() {
        return host;
    }

    public void setHost(Host host) {
        this.host = host;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws IOException {
        loadWebapps();
        //加载Servlet配置
//        loadServlet();


        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("====>>>Minicat Start on port:" + port);

        /*
         完成1。0版本
         （浏览器请求后 http://localhost:8080 返回固定的字符串）
        */
        /*
        while (true) {
            Socket socket = serverSocket.accept();
            String data = "Hello Minicat ";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            //接收的请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(responseText.getBytes());
            socket.close();
        }
        */

        /*
        2.0需求
        封装Request和Response对象，并且返回Html资源
        */
        /*
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            //封装Request和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());

            socket.close();
        }
        */

        /*
        3.0需求
        可以请求动态资源（Servlet）
        */
        /* while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            //封装Request和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            //静态资源处理
            if (servletMap.get(request.getUrl()) == null)
                response.outputHtml(request.getUrl());
            else {
                try {
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            socket.close();
        }

         */

        /*
        多线程改造
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.start();
        }*/

        /*
        线程池改造
         */

        //定义线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                unit, workQueue, threadFactory);
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap, host.getAppBase());
            threadPoolExecutor.execute(requestProcessor);
        }

    }


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();


    private void loadWebapps() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//Service");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element connect = (Element) element.selectSingleNode("Connect");
                String port = connect.attribute("port").getStringValue();
                if (!port.isBlank()) {
                    this.setPort(Integer.parseInt(port));
                }
                Element engine = (Element) element.selectSingleNode("Engine");
                Element host = (Element) engine.selectSingleNode("Host");
                String hostName = host.attribute("name").getStringValue();
                String hostAppBase = host.attribute("appBase").getStringValue();
                // 封装host
                Host host1 = new Host();
                host1.setAppBase(hostAppBase);
                host1.setName(hostName);
                // 读取appBase
                File file = new File(hostAppBase);
                loadWebXml(file);
                this.setHost(host1);

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void loadWebXml(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                if (file1.isFile() && file1.getName().equals("web.xml"))//判断是否是一个文件 并且名字叫web.xml
                {
                    try {
                        InputStream resourceAsStream = new FileInputStream(file1);
                        SAXReader saxReader = new SAXReader();

                        Document document = saxReader.read(resourceAsStream);
                        Element rootElement = document.getRootElement();

                        List<Element> selectNodes = rootElement.selectNodes("//servlet");
                        for (int i = 0; i < selectNodes.size(); i++) {
                            Element element = selectNodes.get(i);
                            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");// <servlet-name>brighton</servlet-name>
                            String servletName = servletnameElement.getStringValue();
                            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");// <servlet-class>server.LagouDemo2Servlet</servlet-class>
                            String servletClass = servletclassElement.getStringValue();
                            // 根据servlet-name的值找到url-pattern
                            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                            // <url-pattern>/brighton</url-pattern>
                            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                            String path = file1.getParentFile().getAbsolutePath();
                            String s = servletClass.replace(".", "/");
//                            String javaName = path + "\\" + s + ".java";
                            String className = path + "/" + s + ".class";
                            // 根据  绝对路径  获取文件然后  将其实例化
                            MyClassLoad myClassLoad = new MyClassLoad();
                            Class<?> aClass = myClassLoad.load(className);
                            //======================================
                            HttpServlet httpServlet = (HttpServlet) aClass.newInstance();
                            servletMap.put("/" + file1.getParentFile().getName() + urlPattern, httpServlet);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (file1.isDirectory()) { //如果是个文件夹再次递归
                    loadWebXml(file1);
                }
            }
        }
    }

    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (Element selectNode : selectNodes) {

                Element servletNameServlet = (Element) selectNode.selectSingleNode("servlet-name");
                String servletName = servletNameServlet.getStringValue();

                Element servletClassServlet = (Element) selectNode.selectSingleNode("servlet-class");
                String servletClass = servletClassServlet.getStringValue();


                //根据ServletName 找到 url-pattern
                Element servletMapping =
                        (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
